package com.hdax.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hdax.common.constant.ProductConstant;
import com.hdax.common.constant.WareConstan;
import com.hdax.gulimall.ware.entity.PurchaseDetailEntity;
import com.hdax.gulimall.ware.entity.WareSkuEntity;
import com.hdax.gulimall.ware.service.PurchaseDetailService;
import com.hdax.gulimall.ware.service.WareSkuService;
import com.hdax.gulimall.ware.vo.MergeVo;
import com.hdax.gulimall.ware.vo.PurchaseDoneItemVo;
import com.hdax.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.common.utils.PageUtils;
import com.hdax.common.utils.Query;

import com.hdax.gulimall.ware.dao.PurchaseDao;
import com.hdax.gulimall.ware.entity.PurchaseEntity;
import com.hdax.gulimall.ware.service.PurchaseService;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {


    @Autowired
    private PurchaseDetailService purchaseDetailService;

    /**
     * 库存
     * @param params
     * @return
     */
    @Autowired
    private WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }


    /**
     * 合并整单
     * @param mergeVo
     */
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //获取采购单的id，采购单的状态为已分配的状态
        Long purchaseId = mergeVo.getPurchaseId();
        //如果没有采购单，则创建新的采购单
        if(purchaseId==null){
            PurchaseEntity purchase=new PurchaseEntity();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            //创建新的采购单为新建状态
            purchase.setStatus(WareConstan.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            //刚刚新建采购单的id
            purchaseId=purchase.getId();
        }
        //采购需求的id
        List<Long> items=mergeVo.getItems();
        //采购单的id
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            //新建采购单
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            //要修改的采购需求的id
            purchaseDetail.setId(item);
            //采购需求绑定对应的采购单
            purchaseDetail.setPurchaseId(finalPurchaseId);
            //修改采购单的状态(已经分配)
            purchaseDetail.setStatus(WareConstan.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetail;
        }).collect(Collectors.toList());

        //修改采购需求
        purchaseDetailService.updateBatchById(collect);

        //修改采购单
        PurchaseEntity purchase = new PurchaseEntity();
        //修改采购单对应的采购需求
        purchase.setId(purchaseId);
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }


    /**
     * 采购人员领取采购单
     * @param purchaseIds
     */
    @Override
    public void received(List<Long> purchaseIds) {
        //1、确认当前采购单是新建或者已经分配状态菜可以领取
        List<PurchaseEntity> collect = purchaseIds.stream().map(item -> {
            //查询采购单的详细信息
            PurchaseEntity byId = this.getById(item);
            return byId;
        }).filter(item->{
            if (item.getStatus() == WareConstan.PurchaseStatusEnum.ASSIGNED.getCode() || item.getStatus() ==WareConstan.PurchaseStatusEnum.CREATED.getCode() ){
                return true;
            }
            return false;
        }).map(item->{
            //修改采购单的状态，已领取
            item.setStatus(WareConstan.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());
        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购项的状态(采购需求)
        collect.forEach(item->{
            //根据采购单的id，来修改采购需求的状态
            List<PurchaseDetailEntity> list=purchaseDetailService.listDetailByPurchaseId(item.getId());

        });

    }

    /**
     * 完成采购
     * @param purchaseDoneVo
     */
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {

        //1、改变采购单的状态

        //获取采购单的ID
        Long id = purchaseDoneVo.getId();
        //2、改变采购单中采购项的状态(采购需求)
        List<PurchaseDetailEntity> list=new ArrayList<>();

        Boolean flag=true;
        //获取采购需求的集合
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        for (PurchaseDoneItemVo item : items) {
            PurchaseDetailEntity purchaseDetail=new PurchaseDetailEntity();
            //采购异常
            if(item.getStatus()==WareConstan.PurchaseDetailStatusEnum.HASERR.getCode()){
                flag=false;
                purchaseDetail.setStatus(WareConstan.PurchaseDetailStatusEnum.HASERR.getCode());
            }else{
                //采购成功进行入库
                purchaseDetail.setStatus(WareConstan.PurchaseDetailStatusEnum.FINISH.getCode());
                //添加库存
                // 1: 当前采购商品的id
                //2：仓库的id
                //3、采购的数量
                //根据采购需求的id获取，
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.andStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());
            }
            purchaseDetail.setId(item.getItemId());
            list.add(purchaseDetail);
        }
        //修改采购需求表的状态
        purchaseDetailService.updateBatchById(list);


        //修改采购单表的状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(id);
        purchase.setStatus(flag?WareConstan.PurchaseDetailStatusEnum.FINISH.getCode():WareConstan.PurchaseStatusEnum.HASERR.getCode());
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
        //3、将成功采购的进行入库


    }

}